<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form
      ref="formRef"
      inline
      label-width="100px"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="菜单类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择菜单类型" clearable>
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item
        v-show="form.type !== 'BUTTON'"
        label="路由地址"
        prop="path"
      >
        <el-input v-model.trim="form.path" placeholder="system" />
      </el-form-item>
      <el-form-item
        v-show="form.type === 'MENU'"
        label="vue组件路径"
        prop="component"
      >
        <el-input v-model.trim="form.component" />
      </el-form-item>
      <el-form-item v-show="form.parentId != '0'" label="父级节点">
        <el-tree-select
          v-model="form.parentId"
          placeholder="请选择父节点"
          :data="treeData"
          filterable
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item
        v-show="form.type === 'MENU' || form.type === 'CATALOG'"
        label="跳转路径"
        prop="redirect"
      >
        <el-input v-model.trim="form.redirect" />
      </el-form-item>
      <el-form-item
        v-show="form.type === 'BUTTON'"
        label="权限标识"
        prop="perm"
      >
        <el-input v-model.trim="form.perm" />
      </el-form-item>
      <el-form-item v-show="form.type === 'CATALOG'" label="排序" prop="perm">
        <el-input v-model.trim="form.sort" />
      </el-form-item>
      <el-form-item
        v-show="form.type === 'MENU' || form.type === 'CATALOG'"
        label="图标"
      >
        <el-popover
          popper-class="icon-selector-popper"
          trigger="hover"
          width="300"
        >
          <template #reference>
            <el-input v-model="form.icon" />
          </template>
          <vab-icon-selector @handle-icon="handleIcon" />
        </el-popover>
      </el-form-item>
      <el-form-item v-show="form.type === 'MENU'" label="是否隐藏">
        <el-switch
          v-model="form.visible"
          :active-value="0"
          :inactive-value="1"
        />
      </el-form-item>
      <el-form-item v-show="form.type === 'MENU'" label="是否无缓存">
        <el-switch
          v-model="form.keepAlive"
          :active-value="0"
          :inactive-value="1"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import VabIconSelector from '@/plugins/VabIconSelector'
  import { doEdit, doAdd, fetchMenusList } from '@/api/menuManagement'

  export default defineComponent({
    name: 'MenuManagementEdit',
    components: { VabIconSelector },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const checkPath = (rule, value, callback) => {
        if (state.form.type !== 'BUTTON' && !value) {
          callback(new Error('请输入路由地址'))
        } else {
          callback()
        }
      }
      const checkComponent = (rule, value, callback) => {
        if (state.form.type === 'MENU' && !value) {
          callback(new Error('请输入组件路径'))
        } else {
          callback()
        }
      }
      const checkPerm = (rule, value, callback) => {
        if (state.form.type === 'BUTTON' && !value) {
          callback(new Error('请输入权限标识'))
        } else {
          callback()
        }
      }
      const state = reactive({
        formRef: null,
        form: {},
        treeData: [],
        rules: {
          type: [
            { required: true, trigger: 'change', message: '请选择菜单类型' },
          ],
          name: [
            { required: true, trigger: 'blur', message: '请输入菜单名称' },
          ],
          path: [
            {
              validator: checkPath,
              trigger: 'blur',
              message: '请输入路由地址',
            },
          ],
          component: [{ validator: checkComponent, trigger: 'blur' }],
          perm: [{ validator: checkPerm, trigger: 'blur' }],
        },
        title: '',
        dialogFormVisible: false,
        typeList: [
          {
            label: '目录',
            value: 'CATALOG',
          },
          {
            label: '菜单',
            value: 'MENU',
          },
          {
            label: '按钮',
            value: 'BUTTON',
          },
          {
            label: '外链',
            value: 'EXTLINK',
          },
        ],
      })

      watch(
        () => state.dialogFormVisible,
        (curVal) => {
          if (curVal) {
            getMenuTreeList()
          }
        }
      )
      const handleIcon = (item) => {
        state.form.icon = item
      }
      const showEdit = (row) => {
        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
          state.form = JSON.parse(JSON.stringify(row))
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const params = JSON.parse(JSON.stringify(state.form))
            if (params.parentId === '' || params.parentId === undefined) {
              params.parentId = '0'
            }
            try {
              const { msg } =
                state.title === '添加'
                  ? await doAdd(params)
                  : await doEdit(params)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (e) {
              console.error(e)
            }
          }
        })
      }

      const getMenuTreeList = async () => {
        try {
          const { data } = await fetchMenusList()
          state.treeData = data
        } catch (e) {
          console.error(e)
        }
      }

      return {
        ...toRefs(state),
        handleIcon,
        showEdit,
        close,
        save,
      }
    },
  })
</script>

<style scoped>
  :deep() .el-form-item {
    width: 100% !important;
  }
</style>
